package com.weisy.signin.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.hjq.toast.ToastUtils;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.weisy.signin.BuildConfig;
import com.weisy.signin.R;
import com.weisy.signin.base.BaseAcativity;
import com.weisy.signin.bean.Student;
import com.weisy.signin.bean.Teacher;
import com.weisy.signin.comm.Comm;
import com.weisy.signin.utils.GsonUtils;
import com.weisy.signin.utils.ImageUtils;
import com.weisy.signin.utils.Logs;
import com.weisy.signin.utils.SpUtils;
import com.weisy.signin.widget.AlbumDialog;
import com.weisy.signin.widget.CircleTransform;
import com.weisy.signin.widget.LoadingDialog;
import com.weisy.signin.widget.WheelDialog;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import androidx.core.content.FileProvider;
import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * @author weisy
 * @function 补充信息
 * @date 2019/3/23 10:05
 */
@Route(path = Comm.ROUTE_EDIT_INFO)
public class EditInfoActivity extends BaseAcativity {
    private final static int REQUEST_CAMERA = 100;
    private final static int REQUEST_ALBUM = 101;
    private final static int REQUEST_CROP = 1002;

    @BindView(R.id.img_edit_head)
    ImageView imgHead;
    @BindView(R.id.line_edit_student)
    LinearLayout lineStudent;
    @BindView(R.id.line_edit_teacher)
    LinearLayout lineTeacher;

    @BindView(R.id.txt_edit_type)
    TextView txtType;
    @BindView(R.id.txt_edit_id)
    TextView txtId;

    //姓名
    @BindView(R.id.edit_real_name)
    EditText editName;
    //手机号
    @BindView(R.id.edit_phone)
    EditText editPhone;

    //专业
    @BindView(R.id.edit_major_name)
    EditText editMajor;
    //年级
    @BindView(R.id.txt_grade_name)
    TextView txtGrade;
    //班级
    @BindView(R.id.edit_class_name)
    EditText editClass;

    //单位
    @BindView(R.id.edit_unit_name)
    EditText editUnit;
    //职称
    @BindView(R.id.edit_teach_title)
    EditText editTitle;
    //授课名称
    @BindView(R.id.edit_course_name)
    EditText editCourse;


    private List<String> grades = Arrays.asList("大一", "大二", "大三", "大四");
    @Autowired
    int userType;

    private Teacher teacher;
    private Student student;

    private String sex = "男";
    private String bitStr = "";

    //图片路径
    private Uri imageUri;
    private String imgUrl;

    @Override
    public void findView() {
        setContentView(R.layout.activity_edit_info);
        ARouter.getInstance().inject(this);
    }

    @Override
    public void initView() {
        String persion = (String) SpUtils.get(context, Comm.SP_PERION, "");
        if (userType == 1) {
            lineStudent.setVisibility(View.VISIBLE);
            lineTeacher.setVisibility(View.GONE);
            student = GsonUtils.str2Bean(persion, Student.class);
            txtType.setText("学号");
            txtId.setText(student.getStudentId());
            if (!TextUtils.isEmpty(student.getName())) {
                editName.setText(student.getName());
            }
            if (!TextUtils.isEmpty(student.getPhone())) {
                editPhone.setText(student.getPhone());
            }

            if (!TextUtils.isEmpty(student.getMajor())) {
                editMajor.setText(student.getMajor());
            }
            if (!TextUtils.isEmpty(student.getGrade())) {
                txtGrade.setText(student.getGrade());
            }
            if (!TextUtils.isEmpty(student.getClasses())) {
                editClass.setText(student.getClasses());
            }
            if (!TextUtils.isEmpty(student.getImgUrl())) {
                Bitmap bitmap = ImageUtils.str2Bitmap(student.getImgUrl());
                Picasso.get().load(ImageUtils.bit2Uri(context, bitmap))
                        .memoryPolicy(MemoryPolicy.NO_CACHE).transform(new CircleTransform())
                        .placeholder(R.drawable.ic_head_default).error(R.drawable.ic_head_default).into(imgHead);
            }

        } else {
            txtType.setText("工号");
            lineStudent.setVisibility(View.GONE);
            lineTeacher.setVisibility(View.VISIBLE);
            teacher = GsonUtils.str2Bean(persion, Teacher.class);
            txtId.setText(teacher.getTeachId());

            if (!TextUtils.isEmpty(teacher.getName())) {
                editName.setText(teacher.getName());
            }
            if (!TextUtils.isEmpty(teacher.getPhone())) {
                editPhone.setText(teacher.getPhone());
            }

            if (!TextUtils.isEmpty(teacher.getUnitName())) {
                editUnit.setText(teacher.getUnitName());
            }
            if (!TextUtils.isEmpty(teacher.getTchTitle())) {
                editTitle.setText(teacher.getTchTitle());
            }
            if (!TextUtils.isEmpty(teacher.getCourse())) {
                editCourse.setText(teacher.getCourse());
            }
            if (!TextUtils.isEmpty(teacher.getImgUrl())) {
                Bitmap bitmap = ImageUtils.str2Bitmap(teacher.getImgUrl());
                Picasso.get().load(ImageUtils.bit2Uri(context, bitmap))
                        .memoryPolicy(MemoryPolicy.NO_CACHE).transform(new CircleTransform())
                        .placeholder(R.drawable.ic_head_default).error(R.drawable.ic_head_default).into(imgHead);
            }
        }
    }

    @Override
    public void initData() {
        initFilePath();
    }

    @OnClick({R.id.btn_edit_submit, R.id.txt_grade_name, R.id.img_edit_head, R.id.img_edit_close})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_edit_head:
                new AlbumDialog.Builder(context)
                        .setOnAlbumListener((dialog, which) -> {
                            dialog.dismiss();
                            AndPermission.with(context)
                                    .runtime()
                                    .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .onGranted(granted -> {
                                        openAlbum();
                                    })
                                    .onDenied(denied -> {
                                        ToastUtils.show("权限被禁止");
                                    }).start();
                        })
                        .setOnCameraListener((dialog, which) -> {
                            dialog.dismiss();
                            AndPermission.with(context)
                                    .runtime()
                                    .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .onGranted(granted -> {
                                        openCamera();
                                    })
                                    .onDenied(denied -> {
                                        ToastUtils.show("权限被禁止");
                                    }).start();
                        }).create().show();

                break;
            case R.id.btn_edit_submit:
                submit();
                break;
            case R.id.txt_grade_name:
                new WheelDialog.Builder(context)
                        .setDatas(grades)
                        .setTitle("选择年级")
                        .setOnResultListener((dialog, piosition) -> {
                            txtGrade.setText(grades.get(piosition));
                            dialog.dismiss();
                        })
                        .create().show();
                break;
            case R.id.img_edit_close:
                finish();
                break;

        }
    }

    @OnCheckedChanged({R.id.radio_sex_1, R.id.radio_sex_2})
    public void onRadioCheck(CompoundButton view, boolean ischanged) {
        switch (view.getId()) {
            case R.id.radio_sex_1:
                if (ischanged) {
                    sex = "男";
                }
                break;
            case R.id.radio_sex_2:
                if (ischanged) {
                    sex = "女";
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAMERA) {
            if (resultCode == RESULT_OK) {
                corpPic(imageUri);
            }
        } else if (requestCode == REQUEST_ALBUM) {
            if (resultCode == RESULT_OK) {
                if (null != data) {
                    imgUrl = ImageUtils.getRealPathFromUri(context, data.getData());
                    // 获取图片文件的uri对象
                    if (Build.VERSION.SDK_INT >= 24) {
                        imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", new File(imgUrl));
                    } else {
                        imageUri = Uri.fromFile(new File(imgUrl));
                    }
                    corpPic(imageUri);
                } else {
                    ToastUtils.show("图片损坏，请重新选择");
                }
            }
        } else if (requestCode == REQUEST_CROP) {
            Bitmap bitmap = ImageUtils.getBitmapFormUri(context, imageUri);
            if (null != bitmap) {
                bitStr = ImageUtils.bitmap2Str(bitmap);
                Picasso.get().load(ImageUtils.bit2Uri(context, bitmap))
                        .memoryPolicy(MemoryPolicy.NO_CACHE).transform(new CircleTransform())
                        .placeholder(R.drawable.ic_head_default).error(R.drawable.ic_head_default).into(imgHead);
            }
        }
    }

    /**
     * 提交修改
     */
    private void submit() {
        if (userType == 1) {
            if (TextUtils.isEmpty(editName.getText().toString().trim())) {
                ToastUtils.show("真实姓名不能为空");
                return;
            }
        } else {
            if (TextUtils.isEmpty(editCourse.getText().toString().trim())) {
                ToastUtils.show("授课名称不能为空");
                return;
            }
        }
        final LoadingDialog loadingDialog = new LoadingDialog.Builder(context)
                .setMsg("操作中...")
                .setBgDark(true)
                .create();
        loadingDialog.show();
        if (userType == 1) {
            student.setName(editName.getText().toString().trim());
            student.setSex(sex);
            student.setPhone(editPhone.getText().toString().trim());
            student.setImgUrl(bitStr);
            student.setMajor(editMajor.getText().toString().trim());
            student.setGrade(txtGrade.getText().toString().trim());
            student.setClasses(editClass.getText().toString().trim());
            SpUtils.put(context, Comm.SP_PERION, GsonUtils.bean2Str(student));
        } else {
            teacher.setName(editName.getText().toString().trim());
            teacher.setSex(sex);
            teacher.setPhone(editPhone.getText().toString().trim());
            teacher.setImgUrl(bitStr);
            teacher.setUnitName(editUnit.getText().toString().trim());
            teacher.setTchTitle(editTitle.getText().toString().trim());
            teacher.setCourse(editCourse.getText().toString().trim());
            SpUtils.put(context, Comm.SP_PERION, GsonUtils.bean2Str(teacher));
        }
        new Handler().postDelayed(() -> {
            loadingDialog.dismiss();
            new LoadingDialog.Builder(context)
                    .setType(LoadingDialog.TYPE_SUCCESS)
                    .setMsg("修改成功")
                    .setOnDismissListener((dialog, which) -> {
                        finish();
                    })
                    .create().show();
        }, 1000);
    }

    /**
     * 初始化文件路径
     */
    private void initFilePath() {
        imgUrl = Environment.getExternalStorageDirectory() + (userType == 1 ? student.getStudentId() : teacher.getTeachId()) + ".jpg";
        Logs.d(TAG, "文件路径：" + imgUrl);
        File takePhotoImage = new File(imgUrl);
        try {
            // 文件存在，删除文件
            if (takePhotoImage.exists()) {
                takePhotoImage.delete();
            }
            // 根据路径名自动的创建一个新的空文件
            takePhotoImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取图片文件的uri对象
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileprovider", new File(imgUrl));
        } else {
            imageUri = Uri.fromFile(new File(imgUrl));
        }
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        // 创建Intent，用于启动手机的照相机拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定输出到文件uri中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        // 启动intent开始拍照
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Logs.d(TAG, "打开相册");
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        albumIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(albumIntent, REQUEST_ALBUM);
    }

    /**
     * 裁剪图片
     */
    private void corpPic(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //以下两行添加，解决无法加载此图片的提示
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1); // 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100); // 输出图片大小
        intent.putExtra("outputY", 100);
        intent.putExtra("scale", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, REQUEST_CROP);
    }
}
